//
//  THJBaseViewController.m
//  THJXHW
//
//  Created by 河南德艺 on 17/3/7.
//  Copyright © 2017年 河南德艺. All rights reserved.
//

#import "THJBaseViewController.h"
#import "SDAutoLayout.h"
#import "MBProgressHUD.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <MJRefresh.h>
@interface THJBaseViewController ()<UITableViewDelegate,UITableViewDataSource>
{
//    UITableView * _tableview;
    UIView *topSearchView;
    CGRect  _tableviewRect;
}
@property(strong,nonatomic)UITableView * tableview;
@end

@implementation THJBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    UINavigationBar *navBar = [UINavigationBar appearance];
//    navBar.barTintColor = COLOR(83, 84, 85, 1);
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
}
-(UITableView*)tableview{
    if(!_tableview){
        _tableview = [[UITableView alloc] initWithFrame:_tableviewRect style:UITableViewStylePlain];
    }
    return _tableview;
}
-(UIView*)creatSearchWithPlaceholderTextColor:(UIColor*)color{
    
    topSearchView  =[[UIView alloc] init];
    topSearchView.backgroundColor = COLOR(255, 113, 61, 1.0);
    topSearchView.frame = CGRectMake(ScreenWidth/4 , 4, ScreenWidth/2, 36);
    topSearchView.layer.masksToBounds = YES;
    topSearchView.layer.cornerRadius = 5;
    [self.navigationController.navigationBar addSubview:topSearchView];
    
    UIImageView *searchImgView = [[UIImageView alloc] init];
    searchImgView.frame = CGRectMake(10, 8, 20, 20);
    [topSearchView addSubview:searchImgView];
    searchImgView.image = kGetImage(@"ss");
    
    UILabel * searchlabel = [[UILabel alloc] init];
    [topSearchView addSubview:searchlabel];
    searchlabel.text = @"大家都在搜硅铁";
    searchlabel.textColor = color;
    searchlabel.sd_layout
    .leftSpaceToView(searchImgView,15)
    .rightSpaceToView(topSearchView,10)
    .topSpaceToView(topSearchView,8)
    .heightIs(20);
    return topSearchView;
}
-(void)setTableviewWithFrame:(CGRect)frame{
    _tableview = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    //_tableview.backgroundColor = SingleColor(grayColor);
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}
//过滤html标签
- (NSString *)removeHTML:(NSString *)html {
    
    NSScanner *theScanner;
    NSString *text = nil;
    theScanner = [NSScanner scannerWithString:html];
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    return html;
}
#pragma mark ------右上角分享按钮------
- (void)setRightNavBtn
{
    UIImage * img = [kGetImage(@"菜单") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *Item = [[UIBarButtonItem alloc] initWithImage:img style:UIBarButtonItemStyleDone target:self action:@selector(shareWithContent:)];
    self.navigationItem.rightBarButtonItem = Item;
}
-(void)shareWithContent:(NSString*)content{
    [self shareWithContent:@"分享内容" Title:@"铁合金现货网App" Url:@"https://itunes.apple.com/cn/app/%E9%93%81%E5%90%88%E9%87%91%E7%8E%B0%E8%B4%A7%E7%BD%91/id1179909421?mt=8"];
}
-(void)shareWithContent:(NSString*)str Title:(NSString*)title Url:(NSString*)url{
     NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:str
                                     images:@[[UIImage imageNamed:@"applogo"]]
                                        url:[NSURL URLWithString:url]
                                      title:title
                                       type:SSDKContentTypeAuto];
    [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   
                   
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           [self shareSuccess];
                       }
                           
                           break;
                           
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                           message:[NSString stringWithFormat:@"%@",nil]
                                                                          delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           [alert show];
                       }
                           
                           break;
                           
                       default:
                           break;
                   }
                   
                   
    }];
}
-(void)shareSuccess{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
    [alertView show];
}

//左边返回按钮
- (void)setUpNav
{
    UIImage * img = [kGetImage(@"返回")imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:img style:UIBarButtonItemStyleDone target:self action:@selector(pop)];
    self.navigationItem.leftBarButtonItem = backItem;
}
- (void)pop
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setGoBackBtn{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    if(KIsiPhoneX){
        btn.frame = CGRectMake(20, 44, 25, 25);
    }else{
        btn.frame = CGRectMake(20, 25, 25, 25);
    }
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}
-(void)HUDShowMsg:(NSString*)msg AfterDelayDimiss:(double)second{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = msg;
    //hud.label.backgroundColor = COLOR(0, 0, 0, 0.7);
    hud.removeFromSuperViewOnHide = YES;
    [hud hideAnimated:YES afterDelay:second];
}
-(void)alertWithTitle1:(NSString*)title1 title2:(NSString*)title2 title3:(NSString*)title3{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:title1 style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self actionSheetIndex0Function];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:title2 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self actionSheetIndex1Function];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:title3 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       [self actionSheetIndex2Function];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
-(void)actionSheetIndex0Function{
    NSLog(@"点击了第一个");
}
-(void)actionSheetIndex1Function{
    NSLog(@"点击了第二个");
}
-(void)actionSheetIndex2Function{
    NSLog(@"点击了第三个");
}
//img 转base64
-(NSString*)imgToBase64:(UIImage*)img{
    NSData *data = UIImagePNGRepresentation(img);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:0];
    
    [NSString stringWithFormat:@"data:%@;base64,%@", @"image/png",encodedImageStr];
    

    return  [NSString stringWithFormat:@"data:%@;base64,%@", @"image/png",encodedImageStr];
}
- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.1);
        mimeType = @"image/jpeg";
    }
    return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
            [imageData base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength]];
}
//导航栏右边发布按钮
- (void)setNavRightFabuBtn
{
    UIBarButtonItem *Item = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(fabu)];
    [Item setTintColor:SingleColor(whiteColor)];
    self.navigationItem.rightBarButtonItem = Item;
}
-(void)fabu{};
- (void)setTextFieldLeftImageView:(UITextField *)textField leftImageName:(NSString *)imageName
{
    // 设置左边图片
    UIImageView *leftView     = [[UIImageView alloc] init];
    leftView.image            = [UIImage imageNamed:imageName];
    leftView.frame = CGRectMake(0, 0, 40, 40);
    
    // 设置leftView的内容居中
    leftView.contentMode      = UIViewContentModeCenter;
    textField.leftView        = leftView;
    
    // 设置左边的view永远显示
    textField.leftViewMode    = UITextFieldViewModeAlways;
    
    // 设置右边永远显示清除按钮
    textField.clearButtonMode = UITextFieldViewModeAlways;
}
-(void)setButtonContentCenter:(UIButton *)button
{
    CGSize imgViewSize,titleSize,btnSize;
    UIEdgeInsets imageViewEdge,titleEdge;
    CGFloat heightSpace = 10.0f;
    
    //设置按钮内边距
    imgViewSize = button.imageView.bounds.size;
    titleSize = button.titleLabel.bounds.size;
    btnSize = button.bounds.size;
    
    imageViewEdge = UIEdgeInsetsMake(heightSpace,0.0, btnSize.height -imgViewSize.height - heightSpace, - titleSize.width);
    [button setImageEdgeInsets:imageViewEdge];
    titleEdge = UIEdgeInsetsMake(imgViewSize.height +heightSpace, - imgViewSize.width, 0.0, 0.0);
    [button setTitleEdgeInsets:titleEdge];
}

/**
 时间戳转时间

 @param tStr 时间戳
 @return 时间
 */
-(NSString*)timeChangeWithString:(NSString*)tStr{
    NSString *str=tStr;
    
    NSTimeInterval time=[str doubleValue];//因为时差问题要加8小时 == 28800 sec
    
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    
    NSLog(@"date:%@",[detaildate description]);
    
    //实例化一个NSDateFormatter对象
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}
//获取当前日期
-(NSString*)getCurrentTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *DateTime = [formatter stringFromDate:date];
    return  DateTime;
}
/**
 设置状态栏颜色
 */
-(void)setStateBarColor:(UIColor*)color{
//    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
//    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
//        statusBar.backgroundColor = color;
//    }
}
/**
 定制导航栏
 */
-(void)setNavBarWithTitle:(NSString*)title{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 30, 24, 24);
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 30, 150, 21)];
    lab.textColor = SingleColor(whiteColor);
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    lab.text = title;
    
}
-(void)setXNavBarWithTitle:(NSString*)title{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 84)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 50, 24, 24);
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 52, 150, 21)];
    lab.textColor = SingleColor(whiteColor);
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    lab.text = title;
    /*
     UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 84)];
     view.backgroundColor = COLOR(83, 84, 85, 1);
     [self.view addSubview:view];
     
     UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
     btn.frame = CGRectMake(15, 50, 24, 24);
     [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
     [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
     [view addSubview:btn];
     
     UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 52, 150, 21)];
     lab.textColor = SingleColor(whiteColor);
     lab.textAlignment = NSTextAlignmentCenter;
     lab.font = [UIFont systemFontOfSize:12];
     [view addSubview:lab];
     lab.text = title;
     
     UIButton * shareBtn = [UIButton buttonWithType:UIButtonTypeSystem];
     shareBtn.frame =CGRectMake(ScreenWidth - 40, 46, 25, 25);
     
     [shareBtn setBackgroundImage:kGetImage(@"zhishuShare") forState:UIControlStateNormal];
     [shareBtn addTarget:self action:@selector(shareBtnAction) forControlEvents:UIControlEventTouchUpInside];
     [view addSubview:shareBtn];
     */
}
-(void)setXClassNavBarWithTitle:(NSString*)title{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 74)];
    view.backgroundColor = COLOR(83, 84, 85, 1);
    [self.view addSubview:view];
    
    
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(15, 50, 20, 20);
    [btn setBackgroundImage:kGetImage(@"返回") forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, 50, 150, 20)];
    lab.textColor = SingleColor(whiteColor);
    lab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:lab];
    lab.text = title;
}
/**
 tableview
 */
-(UITableView*)setTableviewWithFrame:(CGRect)frame RegisterNibNameArr:(NSArray*)nibNameArr ReuseIdentifierArr:(NSArray*)ridArr RowHeight:(NSInteger)rowHeight BgColor:(UIColor*)color IsLoadMore:(BOOL)isLoadMore{
    if(nibNameArr.count == ridArr.count){
        if(!_tableview){
            _tableviewRect = frame;
            self.tableview.delegate = self;
            self.tableview.dataSource = self;
            self.tableview.rowHeight = rowHeight;
            self.tableview.tableFooterView = [UIView new];
            if(isLoadMore){
                self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
            }
            for (NSInteger i = 0;i<nibNameArr.count;i++) {
                NSString * nibName = nibNameArr[i];
                NSString * rid = ridArr[i];
                [self.tableview registerNib:[UINib nibWithNibName:nibName bundle:nil] forCellReuseIdentifier:rid];
            }
            self.tableview.backgroundColor = color;
            [self.view addSubview:self.tableview];
        }
        [self.tableview reloadData];
        return self.tableview;
    }else{
        NSLog(@"nib数组和rid数组不匹配");
        return nil;
    }
}
-(void)loadMore{
    [self.tableview.mj_footer endRefreshing];
}
-(void)SVHUDShow{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setBackgroundColor:COLOR(220, 220, 220, 0.7)];
    [SVProgressHUD show];
}
-(void)SVHUDHiden{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    });
}
@end
